import { createI18n } from 'vue-i18n';
// 只导入默认语言包
import ja from './locales/ja.json';

// 定义语言包类型
export type LocaleMessages = typeof ja;
// 创建 i18n 实例
const i18n = createI18n({
    legacy: false, // 使用 Composition API
    locale: 'ja', // 默认语言
    fallbackLocale: 'ja', // 回退语言
    messages: {
        ja
    },
    datetimeFormats: {
        en: {
            short: {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
            },
            long: {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                weekday: 'short',
                hour: "numeric"
            }
        },
        zh: {
            short: {
                year: 'numeric',
                month: 'short',
                day: 'numeric'
            },
            long: {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                weekday: 'short',
                hour: "numeric"
            }
        },
        ja: {
            short: {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                weekday: 'short',
                hour: "numeric"
            },
            long: {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                weekday: 'short',
                hour: "numeric"
            }
        }
    },
    numberFormats: {
        en: {
            currency: {
                style: 'currency',
                currency: 'USD'
            }
        },
        zh: {
            currency: {
                style: 'currency',
                currency: 'CNY'
            }
        },
        ja: {
            currency: {
                style: 'currency',
                currency: 'JPY'
            }
        }
    }
});
export const supportedLocales = ['en', 'zh', 'ja'] as const;
// 导出常用函数
export const {
    t: $t,
    d: $d,
    n: $n,
    tm: $tm,
    locale,
    fallbackLocale,
    availableLocales
} = i18n.global;
// 添加 watch 方法到 Composer 类型
Object.assign(i18n.global, {
    watch: function (source: any, callback: (newValue: any, oldValue: any) => void, options?: any) {
        // 实现或留空，主要是为了通过类型检查
    }
});
// 类型安全的翻译函数
export const typedT = <Key extends keyof LocaleMessages>(
    key: Key,
    params?: Record<string, any>
): string => {
    return $t(key, params) as string;
};

// 按需加载语言包
export async function loadLanguageAsync(lang: string) {
    // 如果语言包已存在，直接返回
    if (i18n.global.availableLocales.includes(lang as any)) {
        return;
    }
    try {
        const messages = await import(`@/i18n/locales/${lang}.json`);
        i18n.global.setLocaleMessage(lang, messages.default);
    } catch (error) {
        console.error(`Failed to load locale: ${lang}`, error);
        // 回退到默认语言
        i18n.global.locale.value = 'ja';
    }
}

export default i18n;